package com.lyl.filter;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @author lylbell
 * @date 2021-06-17 21:32
 */
@Component
public class TokenCheckFilter implements GlobalFilter, Ordered {

    //设置白名单，即不需要token即可登录
    @Value("${no.token.access.urls:/admin/login,/user/gt/register,/user/login}")
    private Set<String> noTokenAcceddUrls;

    @Autowired
    private StringRedisTemplate redisTemplate;



    /**拦截用户请求后的操作*/
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、判断该接口是否需要token
        if (!isRequiredToken(exchange)) {
            return chain.filter(exchange);
        }

        //2、取出用户的token
        String token = getUserToken(exchange);
        if (StringUtils.isEmpty(token)) {
            return buildNoAuthorizationResult(exchange);
        }
        //3、判断token是否有效
        Boolean isToken = redisTemplate.hasKey(token);
        if (isToken != null && isToken) {
            return chain.filter(exchange);
        }
        return buildNoAuthorizationResult(exchange);
    }

    /**
     * 不存在或者无效token给用户一个反馈
     * @param exchange
     * @return
     */
    private Mono<Void> buildNoAuthorizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error","unauthorized");
        jsonObject.put("errorMsg","TOken is Null or Error");
        DataBuffer wrap = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap));
    }

    /**
     * 获取token
     * @param exchange
     * @return
     */
    private String getUserToken(ServerWebExchange exchange) {
        String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null ? null : token.replace("bearer ","");
    }

    /**
     * 判断是否需要token
     * @param exchange
     * @return
     */
    private boolean isRequiredToken(ServerWebExchange exchange) {
        String path = exchange.getRequest().getURI().getPath();
        if (noTokenAcceddUrls.contains(path)) {
            return false;
        }
        return true;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
